# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import requests,random


class BookinfoSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class BookinfoDownloaderMiddleware(object):
    '''设置Request请求代理IP的下载中间件'''
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    def __init__(self, timeout=None, service_args=[]):
        '''初始化，设置代理池等'''
        
        #设置代理池，申请20个代理IP
        proxies = requests.get('http://api.xdaili.cn/xdaili-api//greatRecharge/getGreatIp?spiderId=6b7535399daf4ad8838bba029e176c31&orderno=YZ201871811160L5ypt&returnType=1&count=20').text
        #每个代理IP在代理池里放3个副本，每失败1次删除1个副本，即有3次失败机会。20个代理IP共60个副本。
        self.proxy_list = proxies.strip("\r\n").split("\r\n") * 3
        
        #讯代理独享代理IP
        #self.pro_addr = 'http://' + requests.get("http://api.xdaili.cn/xdaili-api//privateProxy/getDynamicIP/DD20187312050QPAeui/c70c52387db611e7bcaf7cd30abda612?returnType=1").text
        pass

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        '''设置Request请求的代理IP'''
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        
        last_pro_addr = request.meta.get('proxy','').strip('http://')   #上次请求代理IP

        if last_pro_addr:   #已经设置代理IP，属于上次请求失败重新发起请求的情况
            print("上次请求设置代理：" + last_pro_addr)
            #代理池删除一个上次请求失败的代理IP副本
            if last_pro_addr in self.proxy_list:
                self.proxy_list.remove(last_pro_addr)

            if len(self.proxy_list) <= 57:  #已经减少了3个代理IP副本，需要新申请代理IP
                #新申请一个代理IP
                pro_addr = requests.get('http://api.xdaili.cn/xdaili-api//greatRecharge/getGreatIp?spiderId=6b7535399daf4ad8838bba029e176c31&orderno=YZ201871811160L5ypt&returnType=1&count=1').text.strip("\r\n")
                print("新申请代理IP：" + pro_addr)
                #代理池里添加新申请的代理IP的3个副本
                self.proxy_list.extend([pro_addr] * 3)
            else:
                #从代理池里随机选取一个代理IP
                pro_addr = random.choice(self.proxy_list)

            #重新设置代理IP
            request.meta['proxy'] = 'http://' + pro_addr
            print("重新设置代理"+pro_addr)

        else:               #尚未设置代理IP，属于全新发起请求的情况
            #从代理池里随机选取一个代理
            pro_addr = random.choice(self.proxy_list)
            #设置代理IP
            request.meta['proxy'] = 'http://' + pro_addr
            print("正在使用代理"+pro_addr+"……")
        
        '''
        last_pro_addr = request.meta.get('proxy','').strip('http://')   #上次请求代理IP
        if last_pro_addr:   #已经设置代理IP，属于上次请求失败重新发起请求的情况
            #讯代理独享代理IP
            self.pro_addr = 'http://' + requests.get("http://api.xdaili.cn/xdaili-api//privateProxy/getDynamicIP/DD20187312050QPAeui/c70c52387db611e7bcaf7cd30abda612?returnType=1").text
        request.meta['proxy'] = self.pro_addr
        '''
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
